import config from '../../config';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    info: {},
    coverInfo:null,
    pathUrl: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("options", options);
    this._getAcceptDataFromOpenerPage().then(res => {
      console.log("_getAcceptDataFromOpenerPage", res);
      options = res;
      this.data.coverInfo = this._getCoverInfo(options);
      this.setData({
        coverInfo:this.data.coverInfo
      })
      // let envConfig = this._getEnvUrl(options.env);
      this._getProInfo(options).then(info => {
        if(!options.prodId){
          let path = this._getUrlDetail(options.prodType);
          let fullUrl = info.url.replace('https://', '') + path;
          console.log("path", fullUrl, encodeURIComponent(fullUrl));
          this.setData({
            pathUrl: encodeURIComponent(fullUrl)
          })
          return;
        }
        let prodId = info.prodId,
          prodType = info.prodType,
          query = {
            goodsRoomId: options.socialRoomId
          },
          courseType = options.courseType;
        if (prodType == 1 || prodType == 23) {
          //vip购买
          prodId = info.vipInfo.id;
          if (info.relationType == config.relationTypeMap.collage) {
            query.isCollage = true;
          } else if (info.relationType == config.relationTypeMap.flashSales) {
            query.pId = info.vipInfo.marketID;
            query.type = info.subProdType == 1 ? config.ckFrom.flashSalesVip : config.ckFrom.flashSalesSvip;
          }
        } else if (prodType == 9 || prodType == 67) {
          query.cId = -1;
        } else if (prodType == 76) {
          query.relType = 2;
          query.type = 2;
        } else if (prodType == 78) {
          prodId = info.relationType == config.relationTypeMap.flashSales || info.relationType == config.relationTypeMap.collage ? info.subMsgId : info.subProdId;
        } else if (prodType == 104) {
          query.courseId = -1;
          query.distribution = -1;
        } else if(Object.values(config.ckFrom.agentApplys).includes(prodType * 1)){
          //服务商 用户的vipType表示服务商，3，5，6，7，8，9，10，11，12。从低到高表示1到9级服务商
          console.log("服务商类型");
          query.applyType = info.vipType;
        }
        let path = this._getUrlDetail(prodType, prodId, query, courseType);
        let fullUrl = info.url.replace('https://', '') + path;
        console.log("path", fullUrl, encodeURIComponent(fullUrl));
        this.setData({
          pathUrl: encodeURIComponent(fullUrl)
        })
      })
    });
  },
  _getCoverInfo(data){
    let res=null;
    if(data.prodType==1){
      res ={
        img:"https://ck-bkt-knowledge-payment.oss-cn-hangzhou.aliyuncs.com/admin/material/27_material_admin/image/images/vip_guide_cover.png",
        name:"开通会员"
      }
    }
    return res;
  },
  handleContact(e) {
    console.log(e.detail.path)
    console.log(e.detail.query)
  },
  _getProInfo(options) {
    return new Promise((resolve, reject) => {
      console.log("options.env", options.env)
      let envConfig = this._getEnvUrl(options.env);
      let sendData = {
        prodId: options.prodId || "",
        prodType: options.prodType,
        subProdId: options.subProdId,
        subProdType: options.subProdType,
        relationId: options.relationId,
        relationType: options.relationType
      }
      if (options.detailId) {
        sendData.detailId = options.detailId
      }
      wx.request({
        url: envConfig.reqtUrl + `liveApplet/getGoodsInfo/${options.socialRoomId}`,
        data: sendData,
        dataType: "json",
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Authorization': 'Bearer ' + options.roomToken
        },
        method: "GET",
        success: (res) => {
          console.log("_getProInfo", res.data.data);
          this.setData({
            info: res.data.data
          })
          resolve(res.data.data);
        },
        fail: function (res) {
          console.warn("wxLogin当中wx.request fail 执行了：调用失败")
          reject();
        }
      })
    })
  },
  //接收跳转页面传递的数据
  _getAcceptDataFromOpenerPage: function (options) {
    return new Promise((resolve, reject) => {
      const eventChannel = this.getOpenerEventChannel();
      if (Object.keys(eventChannel).length) {
        eventChannel.on('acceptDataFromOpenerPage', function (data) {
          resolve(data);
        })
      } else {
        resolve(options);
      }
    })
  },

  _getEnvUrl(val) {
    let res = {
      reqtUrl: "",
      pageUrl: ""
    }
    switch (val * 1) {
      case 1:
        res.pageUrl = 'https://kptest.ckjr001.com';
        res.reqtUrl = 'https://kpapi-cs.ckjr001.com/api/';
        break;
      case 2:
        res.pageUrl = 'https://formal.ckjr001.com';
        res.reqtUrl = 'https://formalapi.ckjr001.com/api/';
        break;
      case 3:
        res.pageUrl = '';
        res.reqtUrl = 'https://kpapiop.ckjr001.com/api/';
        break
      default:
        res.pageUrl = '';
        res.reqtUrl = 'https://kpapiop.ckjr001.com/api/';
    }
    return res;
  },

  // 获取需要跳转的路由详情
  _getUrlDetail(prodType, prodId, query, courseType, sortType) {
    let ckFrom = prodType;
    console.log("ckFrom", ckFrom);
    // 默认ckFrom 为 prodType， 如果需要另外赋值，需要在query.ckFrom赋值然后替换
    // (课程、专栏、训练营、题库、教务、预约才有ckFrom)，对应值为[5, 25, 30, 66, 9, 24, 26, 29, 38, 67, 103, 104, 78, 91, 146, 8076, 9078, 129, 9042, 116, 9043, 86]
    if (query && query.ckFrom) {
      ckFrom = ckFrom != query.ckFrom ? query.ckFrom : ckFrom;
      delete query.ckFrom;
    }
    // (砍价 || 拼团 || 限时购 || 好友助力) && 类型为vip或svip  需要跳转到vipCollage
    if (query && (query.isBargain || query.isCollage || query.isSales || query.isFa) && (prodType == global.ckFrom.vip || prodType == global.ckFrom.svip)) {
      prodType = global.ckFrom.vip ? global.ckFrom.collageVip : global.ckFrom.collageSvip;
    }
    // 判断是跳转详情还是列表
    if (query && query.isList) {
      prodType = query.isList == 1 ? (prodType + '-1') : prodType;
      delete query.isList;
    }
    // typeToUrl 的 key 是 config.js中对应的 global.ckFrom值
    let typeToUrl = {
      '1': `/member/vip/vipUp?type=${prodType}`,
      '5': `/homePage/course/${courseType == 0 ? 'video' : courseType == 1 ? 'voice' : 'imgText'}?courseId=${prodId}&ckFrom=${ckFrom}`,
      '7': `/activity/activityDetail?ActivityNo=${prodId}`,
      '8': `/homePage/datum/datumDetail?datumId=${prodId}`,
      '9': `/homePage/column/columnDetail?extId=${prodId}&ckFrom=${ckFrom}`,
      '10': `/homePage/socialGroup/socialGroupInfo?SocialRoomId=${prodId}`,
      '11': `/homePage/examination/examinationDetail?ExaminationNo=${prodId}`,
      '12': `/mall/shopDetail/shopDetail?ShopNo=${prodId}`,
      '15': `/homePage/qa/questionDetail?answerId=${prodId}`,
      '16': `/homePage/qa/answerDetail?questionDetailId=${prodId}`,
      '17': `/homePage/qa/answerDetail?questionDetailId=${prodId}`,
      '23': `/member/vip/vipUp?type=${prodType}`,
      '24': `/homePage/column/columnDetail?extId=${prodId}&ckFrom=${ckFrom}`,
      '25': `/homePage/course/${courseType == 0 ? 'video' : courseType == 1 ? 'voice' : 'imgText'}?courseId=${prodId}&ckFrom=${ckFrom}`,
      '26': `/homePage/column/columnDetail?extId=${prodId}&ckFrom=${ckFrom}`,
      '27': `/member/vip/vipUp?type=${prodType}`,
      '28': `/member/vip/vipUp?type=${prodType}`,
      '29': `/homePage/column/columnDetail?extId=${prodId}&ckFrom=${ckFrom}`,
      '30': `/homePage/course/${courseType == 0 ? 'video' : courseType == 1 ? 'voice' : 'imgText'}?courseId=${prodId}&ckFrom=${ckFrom}`,
      '31': `/homePage/collage/vipCollage?prodId=${prodId}`,
      '32': `/homePage/collage/vipCollage?prodId=${prodId}`,
      '36': `/activity/activityDetail?ActivityNo=${prodId}`,
      '38': `/homePage/column/columnDetail?extId=${prodId}&ckFrom=${ckFrom}`,
      '41': `/homePage/clockIn/clockInDetail?clockInId=${prodId}`,
      '48': `/homePage/package/packageDetail?combosId=${prodId}`,
      '51': `/homePage/live/liveDetail?liveId=${prodId}`,
      '53': `/activity/activityDetail?ActivityNo=${prodId}&from=reservation`,
      '56': `/homePage/word/wordDetail?dId=${prodId}`,
      '61': `/homePage/package/packageDetail?combosId=${prodId}`,
      '62': `/homePage/package/packageDetail?combosId=${prodId}`,
      '66': `/homePage/course/${courseType == 0 ? 'video' : courseType == 1 ? 'voice' : 'imgText'}?courseId=${prodId}&ckFrom=${ckFrom}`,
      '67': `/homePage/column/columnDetail?extId=${prodId}&ckFrom=${ckFrom}`,
      '68': `/homePage/collage/vipCollage?prodId=${prodId}`,
      '69': `/homePage/collage/vipCollage?prodId=${prodId}`,
      '70': `/homePage/package/packageDetail?combosId=${prodId}`,
      '71': `/homePage/examination/examinationDetail?ExaminationNo=${prodId}`,
      '72': `/homePage/live/liveDetail?liveId=${prodId}`,
      '75': `/homePage/mutuaTest/mutuaTestDetail?mutuaTestId=${prodId}`,
      '76': `/homePage/form?relId=${prodId}`,
      '77': `/homePage/VoiceTest/VoiceTestDetail?paperMainId=${prodId}`,
      '78': `/homePage/camp/campDetail?campId=${prodId}&ckFrom=${ckFrom}`,
      '86': `/homePage/booking/bookingTime?atId=${prodId}&ckFrom=${ckFrom}`,
      '91': `/homePage/camp/campDetail?campId=${prodId}&ckFrom=${ckFrom}`,
      '103': `/homePage/column/columnDetail?extId=${prodId}&distribution=1&ckFrom=${ckFrom}`,
      '104': `/homePage/column/columnDetail?extId=${prodId}&distribution=1&ckFrom=${ckFrom}`,
      '115': `/homePage/privateClass/classDetail?classId=${prodId}`,
      '116': `/edu/eduDetail?id=${prodId}&ckFrom=${ckFrom}`,
      '124': `/homePage/live/liveDetail?liveId=${prodId}`,
      '125': `/homePage/testPaper/testDetail?testId=${prodId}`,
      '129': `/homePage/itemBank/questionSaleDetail?libraryId=${prodId}&ckFrom=${ckFrom}`,
      '142': `/homePage/ebooks/ebooksDetail?id=${prodId}`,
      '181': `/homePage/circle/circleFeed?id=${prodId}`,
      '185': `/homePage/circle/circleTheme?themeId=${prodId}`,
      '145': `/homePage/ebooks/ebooksDetail?id=${prodId}`,
      '146': `/homePage/camp/campDetail?campId=${prodId}&ckFrom=${ckFrom}`,
      '155': `/mall/shopComments/shopCommentDetail?id=${prodId}`,
      '180': `/homePage/live/livePersonalDetail?liveId=${prodId}`,
      '8075': `/homePage/clockIn/clockInDetail?clockInId=${prodId}`,
      '8076': `/homePage/camp/campDetail?campId=${prodId}&ckFrom=${ckFrom}`,
      '8077': `/homePage/socialGroup/socialGroupInfo?SocialRoomId=${prodId}`,
      '8078': `/activity/activityDetail?ActivityNo=${prodId}&from=reservation`,
      '8079': `/homePage/VoiceTest/VoiceTestDetail?paperMainId=${prodId}`,
      '8080': `/homePage/mutuaTest/mutuaTestDetail?mutuaTestId=${prodId}`,
      '8081': `/activity/activityDetail?ActivityNo=${prodId}`,
      '8083': `/homePage/ebooks/ebooksDetail?id=${prodId}`,
      '8084': `/homePage/privateClass/classDetail?classId=${prodId}`,
      '9010': `/homePage/socialGroup/socialGroupInfo?SocialRoomId=${prodId}`,
      '9041': `/homePage/clockIn/clockInDetail?clockInId=${prodId}`,
      '9042': `/homePage/itemBank/questionSaleDetail?libraryId=${prodId}&ckFrom=${ckFrom}`,
      '9043': `/edu/eduDetail?id=${prodId}&ckFrom=${ckFrom}`,
      '9044': `/homePage/ebooks/ebooksDetail?id=${prodId}`,
      '9045': `/homePage/live/livePersonalDetail?liveId=${prodId}`,
      '9078': `/homePage/camp/campDetail?campId=${prodId}&ckFrom=${ckFrom}`,
      "5-1": `/homePage/course/courseList${sortType == 0 ? '' : '?sortType=' + sortType}`, //课程列表
      "7-1": "/activity/activityIndex", //活动
      "8-1": "/homePage/datum/datumList", //资料
      "9-1": "/homePage/column/columnList", //专栏
      "10-1": "/homePage/socialGroup/socialGroupList", //社群
      "11-1": "/homePage/examination/examinationList", //测评
      "13-1": `/homePage/microPage/microPage?mId=${prodId}`, //商城
      "15-1": "/homePage/qa/answerLord", //问答
      "41-1": "/homePage/clockIn/clockInList", //打卡
      "51-1": "/homePage/live/liveList", //直播
      "56-1": "/homePage/word/wordList", //词典列表
      "61-1": "/homePage/package/packageList", //知识套餐
      "78-1": "/homePage/camp/campList", //训练营
      "86-1": "/homePage/booking/bookingList", //预约
      "92-1": "/homePage/valueVoucher/list", //优惠券
      "115-1": "/homePage/privateClass/classList", //小班课列表
      "116-1": "/edu/eduList", //教务
      "121-1": "/homePage/collage/collageList", //特惠专区列表
      "125-1": "/homePage/testPaper/testList", //试卷
      "129-1": "/homePage/itemBank/questionList", //题库评
      "137-1": "/homePage/task/taskList", //任务列表
      "170-1": "/homePage/course/courseForenotice", //预告
      "200": `/homePage/shareholder/shCouponDetail?id=${prodId}&rcdId=`, //股东代金券
      "400": `/homePage/microPage/microPage?mId=${prodId}&isPromotedAccount=1`, //子账号推广微页面
      "42": `/homePage/agent/agentDesc`,
      "43": `/homePage/agent/agentDesc`,
      "44": `/homePage/agent/agentDesc`,
      "138": `/homePage/agent/agentDesc`,
      "139": `/homePage/agent/agentDesc`,
      "160": `/homePage/agent/agentDesc`,
      "161": `/homePage/agent/agentDesc`,
      "162": `/homePage/agent/agentDesc`,
      "163": `/homePage/agent/agentDesc`
    }
    let moreUrl = typeToUrl[prodType];
    console.log("moreUrl", moreUrl);
    if (!moreUrl) {
      return '';
    }
    if (query && typeof query == 'object') {
      for (let key in query) {
        moreUrl += (moreUrl.indexOf('?') == -1 ? '?' : '&') + `${key}=${query[key]}`
      }
    }
    return moreUrl.substring(1)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})